package com.sxbbc.common.basics.utils.statics;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.google.common.collect.Lists;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.function.common.GetRest;
import com.function.common.RestResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

public class FunctionUtils {

    /**
     * @param input 输入集合
     * @param clzz  输出集合类型
     * @param <E>   输入集合类型
     * @param <T>   输出集合类型
     * @return 返回集合
     */
    public static <E, T> List<T> convertList2List(List<E> input, Class<T> clzz) {
        List<T> output = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(input)) {
            for (E source : input) {
                T target = BeanUtils.instantiate(clzz);
				BeanUtils.copyProperties(source, target);
                output.add(target);
            }
        }
        return output;
    }

    /**
     * 富文本图片上传
     *
     * @param file 文件
     * @author leehao
     */
    //TODO 富文本图片上传中需要重寫文件上傳的方法
    public static Object uploadFile(MultipartFile file) {
        JSONObject json = new JSONObject();
        if (file != null) {
            try {
                RestUploadFileInfo result =UploadUtils.getInstance().uploadFileQN(file);
                if (!result.isStatus()) {
                    json.put("state", "FAIL");
                } else {
                    json.put("state", "SUCCESS");
                    json.put("url", result.getData());
                    json.put("size", file.getSize());
                    json.put("original", file.getOriginalFilename());
                    json.put("title", file.getOriginalFilename());
                    json.put("type", file.getContentType());
                }
            } catch (Exception e) {
                json.put("state", "FAIL");
            }
        }
        return json;
    }

    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String replay(String phone) {
        String str = phone;
        if (phone.length() > 3) {
            str = phone.substring(0, 3);
            str += "****";
        }
        if (phone.length() > 7) {
            str += phone.substring(7);
        }
        return str;
    }

    /**
     * 字符串编码转换的实现方法
     *
     * @param str        待转换的字符串
     * @param newCharset 目标编码
     */
    public String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
        if (str != null) {
            // 用默认字符编码解码字符串。与系统相关，中文windows默认为GB2312
            byte[] bs = str.getBytes();
            return new String(bs, newCharset); // 用新的字符编码生成字符串
        }
        return null;
    }

    /**
     * 字符串数组转字符串 JDK 1.8+
     *
     * @param arr 字符串数组
     * @return
     * @author WahYee
     * @date 2018年5月18日 上午9:35:48
     */
    public static String strArrToStr(String[] arr) {
        // TODO 元素空处理
        return String.join(",", arr);
    }

    /**
     * 字符串List集合转字符串 JDK 1.8+
     *
     * @param list 字符串集合
     * @return
     * @author WahYee
     * @date 2018年5月18日 上午9:38:30
     */
    public static String strListToStr(List<String> list) {
        // TODO 元素空处理
        return String.join(",", list);
    }

    /**
     * 字符串数组转list int对象
     *
     * @param arr
     * @return
     */
    public static List<Integer> getIntegerList(String[] arr) {
        List<Integer> list = new ArrayList<Integer>();
        for (String s : arr) {
            if (!StringUtils.isEmpty(s)) {
                Integer a = Integer.parseInt(s);
                list.add(a);
            }
        }
        return list;
    }

    /**
     * 字符串数组转list int对象 JDK1.8+  (有问题)
     *
     * @param context 字符串内容
     * @param regex   字符串分隔符
     * @return
     */
//    public static List<Integer> stringCoverInterList(String context, String regex) {
//        return Arrays.asList(context.split("regex")).stream()
//                .map(s -> Integer.parseInt(s))
//                .collect(Collectors.toList());
//    }

    public static void main(String[] args) {
        List<Integer> integers = FunctionUtils.getIntegerList("85165,85166", ",");
        System.out.println(integers);

    }
    /**
     * 字符串数组转list int对象
     *
     * @param arr
     * @return
     */
    public static List<BigDecimal> getBigDecimalList(String[] arr) {
        List<BigDecimal> list = new ArrayList<BigDecimal>();
        for (String s : arr) {
            if (!StringUtils.isEmpty(s)) {
                BigDecimal a = new BigDecimal(s);
                list.add(a);
            }
        }
        return list;
    }

    public static Integer[] getArr(String[] arr) {

        Integer[] intArr = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            String s = arr[i];
            if (!StringUtils.isEmpty(s)) {
                Integer a = Integer.parseInt(s);
                intArr[i] = a;
            }
        }
        return intArr;
    }

    /***
     * 数组(逗号分隔)转list int对象
     *
     * @param str
     * @param reg
     * @return
     */
    public static List<Integer> getIntegerList(String str, String reg) {
        List<Integer> intList = new ArrayList<Integer>();
        if (!StringUtils.isBlank(str)) {
            String[] split = str.split(reg);
            for (String item : split) {
                if (!StringUtils.isBlank(item)) {
                    Integer a = Integer.parseInt(item);
                    intList.add(a);
                }
            }
        }
        return intList;
    }

    /**
     * 字符串数组转list int对象
     *
     * @param arr
     * @return
     */
    public static List<Integer> getList(Integer[] arr) {
        List<Integer> list = new ArrayList<Integer>();
        for (Integer s : arr) {
            if (s != null) {
                list.add(s);
            }
        }
        return list;
    }

    public static List<String> getStrList(Integer[] arr) {
        List<String> list = new ArrayList<String>();
        for (Integer s : arr) {
            if (s != null) {
                list.add(String.valueOf(s));
            }
        }
        return list;
    }

    public static List<String> getStrList(String[] arr) {
        List<String> list = new ArrayList<String>();
        for (String s : arr) {
            if (!StringUtils.isBlank(s)) {
                list.add(s);
            }
        }
        return list;
    }

    /**
     * 字符串数组转list int对象
     *
     * @param arr
     * @return
     */
    public static Set<Integer> getSet(String[] arr) {
        Set<Integer> list = new HashSet<Integer>();
        for (String s : arr) {
            if (!StringUtils.isEmpty(s)) {
                Integer a = Integer.parseInt(s);
                list.add(a);
            }
        }
        return list;
    }

    public static Set<String> getStrSet(String[] arr) {
        Set<String> list = new HashSet<String>();
        for (String s : arr) {
            if (!StringUtils.isEmpty(s)) {
                list.add(s);
            }
        }
        return list;
    }

    public static String getString(List<String> list) {
        String str = "";
        for (String o : list) {
            str += o + ",";
        }
        if (str.length() > 0) {
            return str.substring(0, str.length() - 1);
        } else {
            return str;
        }
    }

    public static String getStringByINT(List<Integer> list) {
        String str = "";
        for (Integer o : list) {
            str += o + ",";
        }
        if (str.length() > 0) {
            return str.substring(0, str.length() - 1);
        } else {
            return str;
        }
    }

    public static String getString(Integer[] list) {
        String str = "";
        for (Integer o : list) {
            str += o + ",";
        }
        if (str.length() > 0) {
            return str.substring(0, str.length() - 1);
        } else {
            return str;
        }
    }

    /**
     * 字符串数组转list int对象 倒叙
     *
     * @param arr
     * @return
     */
    public static List<Integer> getListDesc(String[] arr) {
        List<Integer> list = new ArrayList<Integer>();
        if (arr != null && arr.length > 0) {
            for (int i = arr.length - 1; i > -1; i--) {
                String s = arr[i];
                if (!StringUtils.isEmpty(s)) {
                    Integer a = Integer.parseInt(s);
                    list.add(a);
                }
            }
        }
        return list;
    }

    /**
     * 字符串数组转list int对象 倒叙 只去几位
     *
     * @param arr
     * @return
     */
    public static List<Integer> getListDesc(String[] arr, Integer b) {
        List<Integer> list = new ArrayList<Integer>();
        Integer c = 0;
        for (int i = arr.length - 1; i > -1; i--) {
            if (c < b) {
                String s = arr[i];
                if (!StringUtils.isEmpty(s)) {
                    Integer a = Integer.parseInt(s);
                    list.add(a);
                    c++;
                }
            }
        }
        return list;
    }

    public static void getPrint(HttpServletResponse response, String msg) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void getWriter(HttpServletResponse response, String msg) {
        try {
            response.getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /***
     * 取出两个set中互斥的元素
     *
     * @param sour1
     * @param sour2
     * @return
     */
    public static ArrayList mutexBySet(Set<BigDecimal> sour1, Set<BigDecimal> sour2) {
        ArrayList<String> arrayList = new ArrayList<>();
        Set<BigDecimal> result = new HashSet<BigDecimal>();
        result.clear();
        result.addAll(sour1);
        result.removeAll(sour2);
        for (BigDecimal str : result) {
            arrayList.add(str.toString());
        }
        result.clear();
        result.addAll(sour2);
        result.removeAll(sour1);
        for (BigDecimal str : result) {
            arrayList.add(str.toString());
        }
        return arrayList;
    }

    /***
     * 返回Rest风格数据
     *
     * @param i
     * @param
     * @return
     */
    public static RestResponse ReturnInfo(int i, String successMsg, String errorMsg) {
        if (i > 0) {
            return GetRest.getSuccess(successMsg);
        } else {
            return GetRest.getFail(errorMsg);
        }
    }

    /***
     * 返回Rest风格数据
     *
     * @param
     * @param
     * @return
     */
    public static RestResponse ReturnInfo(boolean flag, String successMsg, String errorMsg) {
        if (flag) {
            return GetRest.getSuccess(successMsg);
        } else {
            return GetRest.getFail(errorMsg);
        }
    }

    /**
     * 判断当前list集合是否包含对象
     *
     * @param arr
     * @param targetValue
     * @return
     */
    public static boolean exist_List_int(List<Integer> arr, Integer targetValue) {
        return arr.contains(targetValue);
    }

    /**
     * 判断当前list集合是否包含对象
     *
     * @param arr
     * @param targetValue
     * @return
     */
    public static boolean exist_List_string(List<String> arr, String targetValue) {
        return arr.contains(targetValue);
    }

    public static String getFirstLetter(String content) {
        String letter = "";
        if (!StringUtils.isBlank(content) && content.length() > 0) {
            letter = content.substring(0, 1).toUpperCase();
        }
        return letter;
    }

    /**
     * 集合分组
     *
     * @param list
     * @param step 步长
     * @return
     * @author Wahyee
     */
    public static <T> List<List<T>> listGroup(List<T> list, Integer step) {
        int limit = (list.size() + step - 1) / step;
        List<List<T>> r = new ArrayList<List<T>>();
        r = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(
                a -> list.stream().skip(a * step).limit(step).parallel().collect(
                        Collectors.toList())).collect(Collectors.toList());
        return r;
    }

}
